import React,{PureComponent} from 'react';
import { Form, Input, Button, Divider, Cascader, Card, Icon, Upload, Radio, InputNumber} from 'antd';
import { routerRedux } from 'dva/router';
import constants from '../../../common/constants';
import styles from './goodsManage.less';
const FormItem = Form.Item;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import {message} from "antd/lib/index";
import LzEditorCom from '../../../components/LzEditor/index';

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

let goodsPhotoList = [];
let goods_desc = '';
export default class GoodsGI extends PureComponent {

    state = {
        loading: false,
        goodsCategory: [],
        brand: [],
        imageUrl: '',
        goods_desc: this.props.data.goods_desc
    };

    componentDidMount() {
        goodsPhotoList = [];
        const {dispatch,goodsPhoto} = this.props;
        goodsPhoto.map(function (k) {
            goodsPhotoList.push(k.name);
        })
        dispatch({
            type: 'brand/queryAll',
            callback: (response) => {
                if (response.result === 0) {
                    this.setState({
                        brand: response.resultData.brandList
                    })

                }
            }
        });
    }

    onPrev = () => {
        const {dispatch} = this.props;
        dispatch(routerRedux.push('/goods/addGoods'));
    };
    onValidateForm = (e) => {
        const {dispatch} = this.props;
        const editType = this.props.data.editType;
        if (editType === 'mod'){
            this.props.form.validateFieldsAndScroll((err, values) => {

                values.goods_photo = goodsPhotoList;
                values.goods_desc = goods_desc;
                if (!err) {
                    dispatch({
                        type: 'goodsManage/keepData',
                        payload: {
                            ...values,
                        },
                    });
                    dispatch(routerRedux.push('/goods/addGoods/goodsSI'));
                }
            });
        }else {
            const goods_sn = this.props.form.getFieldValue("goods_sn");
            dispatch({
                type: 'goodsManage/goodsSn',
                payload: {
                    goods_sn: goods_sn,
                },
                callback: (response) => {
                    if (response.result === 0) {
                        this.props.form.validateFieldsAndScroll((err, values) => {
                            values.goods_desc = goods_desc;
                            if (!err) {
                                dispatch({
                                    type: 'goodsManage/keepData',
                                    payload: {
                                        ...values,
                                    },
                                });
                                dispatch(routerRedux.push('/goods/addGoods/goodsSI'));
                            }
                        });
                    }else {
                        message.error("商品货号已存在")
                    }
                }
            });
        }
    }
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                imageUrl,
                loading: false,
            }));
        }
    }

    normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && `${e.file.response[0].fileUrl}`;
    }

    normFileList = (e) => {
        goodsPhotoList = [];
        e.fileList.map(function (k,index) {
            e.fileList[index].response ?  goodsPhotoList.push(k.response[0].fileUrl) : goodsPhotoList.push(k.name);
        });
        return goodsPhotoList;

    }

    getGoodDesc = (goodsDesc) => {
        goods_desc = goodsDesc;
    }
//单步骤保存
    stepSubmit = (e) => {
        const {dispatch, data} = this.props;
        this.props.form.validateFieldsAndScroll((err, values) => {
            values.goods_photo = goodsPhotoList;
            values.goods_desc = goods_desc;
            if (!err) {
                let user_id = '';
                const userInfoState = sessionStorage.getItem("userInfoState");
                if (userInfoState !== null) {
                    const {userInfo} = JSON.parse(userInfoState);
                    user_id = userInfo.user_id;
                }
                dispatch({
                    type: 'goodsManage/keepData',
                    payload: {
                        ...values,
                    },
                    callback: (response) => {
                        if (response){
                            const editType = data.editType;
                            this.props.goodsGISubmit(editType,user_id,values);
                        }
                    }
                });
            }
        });
    }

    render() {
        const { formItemLayout, data, submitting, goodsPhoto} = this.props;
        const {getFieldDecorator} = this.props.form;
        let brandId = data.editType === 'add' ? [] : eval("["+data.brand_id+"]");
        let goods_photo = data.editType === 'add' ? [] : goodsPhoto;
        const isDisplay=data.editType==='add'?true:false;

        const props = {
            data:{token:"test1"},
            action: constants.fileServer,
            listType: 'picture',
            defaultFileList: [...goodsPhoto],
        };

        const imageUrl = this.state.imageUrl;
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传</div>
            </div>
        );
        return(
            <Card title="一般信息" bordered={false}>
                <Form layout="horizontal" className={styles.stepForm}>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品分类</span>}
                    >
                        {getFieldDecorator('cat_id', {
                            initialValue: data.category,
                            rules: [{
                                type: "array"
                            }],
                        })(
                            <Cascader options={data.goodsCategory} changeOnSelect disabled />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="商品唯一货号"
                    >
                        {getFieldDecorator('goods_sn', {
                            initialValue: data.goods_sn || '',
                            rules: [{
                            }],
                        })(
                            <Input placeholder="商品唯一货号" />
                        )}<em className={styles.optional}>如果不填写则系统自动生成一个唯一的商品货号</em>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品名称</span>}
                    >
                        {getFieldDecorator('goods_name', {
                            initialValue: data.goods_name || '',
                            rules: [{
                                required: true, message: '请输入商品名称',
                            }],
                        })(
                            <Input placeholder="商品名称"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品关键字</span>}
                    >
                        {getFieldDecorator('keywords', {
                            initialValue: data.keywords ||'',
                            rules: [{
                                required: true, message: '请输入商品关键字',
                            }],
                        })(
                            <Input placeholder="商品关键字"/>
                        )}
                    </FormItem>
                    <FormItem
                        label={<span>商品的简短描述</span>}
                    >
                        {getFieldDecorator('goods_brief', {
                            initialValue:  data.goods_brief ||'',
                            rules: [{
                            }],
                        })(
                            <TextArea rows={4} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>本店售价</span>}
                    >
                        {getFieldDecorator('shop_price', {
                            initialValue: data.shop_price || 0 ,
                            rules: [{
                                type: "number",
                                required: true, message: '请输入本店售价',
                            }],
                        })(
                            <InputNumber min={0} step={0.1} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>市场售价</span>}
                    >
                        {getFieldDecorator('market_price', {
                            initialValue: data.market_price || 0,
                            rules: [{
                                type: "number",
                            }],
                        })(
                            <InputNumber min={0} step={0.1} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>成本价</span>}
                    >
                        {getFieldDecorator('cost_price', {
                            initialValue: data.cost_price || 0,
                            rules: [{
                                type: "number",
                            }],
                        })(
                            <InputNumber min={0} step={0.1} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>供货价</span>}
                    >
                        {getFieldDecorator('supply_price', {
                            initialValue:  data.supply_price || 0,
                            rules: [{
                                type: "number",
                            }],
                        })(
                            <InputNumber min={0} step={0.1} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品的重量<em className={styles.optional}>（千克）</em></span>}
                    >
                        {getFieldDecorator('goods_weight', {
                            initialValue: data.goods_weight || 0,
                            rules: [{
                                type: "number",
                            }],
                        })(
                            <InputNumber min={0} step={0.1} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品库存数量</span>}
                    >
                        {getFieldDecorator('goods_number', {
                            initialValue: data.goods_number || 1000,
                            rules: [{
                                type: 'integer',
                                required: true, message: '商品库存数量必须为整数且不能为空',
                            }],
                        })(
                            <InputNumber min={0} step={1} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品报警数量</span>}
                    >
                        {getFieldDecorator('warn_number', {
                            initialValue: data.warn_number ||  1,
                            rules: [{
                                type: 'integer',
                                required: true, message: '商品报警数量必须为整数且不能为空',
                            }],
                        })(
                            <InputNumber min={0} step={1} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品品牌</span>}
                    >
                        {getFieldDecorator('brand_id',{
                            initialValue: brandId || [],
                            rules: [{
                                type: 'array',
                                required: true, message: '请输入商品品牌',
                            }],
                        } )(
                            <Cascader options={this.state.brand} changeOnSelect  />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="是否是实物"
                    >
                        {getFieldDecorator('is_real', {
                            initialValue: data.is_real ? 1 : 0,
                            rules: [{
                                type: 'number',
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={1}>是</Radio>
                                <Radio value={0}>否</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    {/*<FormItem*/}
                        {/*{...formItemLayout}*/}
                        {/*label="是否开放销售"*/}
                    {/*>*/}
                        {/*{getFieldDecorator('is_on_sale', {*/}
                            {/*initialValue: data.is_on_sale ? 1 : 0,*/}
                            {/*rules: [{*/}
                                {/*type: 'number',*/}
                                {/*required: true, message: '请选择',*/}
                            {/*}],*/}
                        {/*})(*/}
                            {/*<RadioGroup>*/}
                                {/*<Radio value={1}>是</Radio>*/}
                                {/*<Radio value={0}>否</Radio>*/}
                            {/*</RadioGroup>*/}
                        {/*)}*/}
                    {/*</FormItem>*/}
                    <FormItem
                        {...formItemLayout}
                        label="是否能单独销售"
                    >
                        {getFieldDecorator('is_alone_sale', {
                            initialValue: data.is_on_sale ? 1 : 0,
                            rules: [{
                                type: 'number',
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={1}>是</Radio>
                                <Radio value={0}>否</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="显示顺序"
                    >
                        {getFieldDecorator('sort_order', {
                            initialValue: data.sort_order || 100
                        })(
                            <Input placeholder=""/>
                        )}<em className={styles.optional}>数字越大顺序越靠后</em>
                    </FormItem>
                    {/*<FormItem*/}
                        {/*{...formItemLayout}*/}
                        {/*label="是否删除"*/}
                    {/*>*/}
                        {/*{getFieldDecorator('is_delete', {*/}
                            {/*initialValue: data.is_delete ? 1 : 0,*/}
                            {/*rules: [{*/}
                                {/*type: 'number'*/}
                                {/*// required: true, message: '请选择',*/}
                            {/*}],*/}
                        {/*})(*/}
                            {/*<RadioGroup>*/}
                                {/*<Radio value={1}>是</Radio>*/}
                                {/*<Radio value={0}>否</Radio>*/}
                            {/*</RadioGroup>*/}
                        {/*)}*/}
                    {/*</FormItem>*/}
                    <FormItem
                        {...formItemLayout}
                        label="实际大小图片"
                    >
                        {getFieldDecorator('goods_img', {
                            initialValue: `${data.goods_img}` || '',
                            getValueFromEvent: this.normFile,
                            rules: [{
                                required: true, message: '请上传商品图片',
                            }],
                        })(
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={constants.fileServer}
                                onChange={this.handleChange}
                            >
                                {
                                    !imageUrl ?
                                    data.goods_img ? <img src={`${constants.imageUrlFix}${data.goods_img}`} alt="" /> : uploadButton
                                    : <img src={imageUrl} alt="" />
                                }

                            </Upload>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="商品相册"
                    >
                        {getFieldDecorator('goods_photo', {
                            initialValue: goods_photo || [],
                            getValueFromEvent: this.normFileList,
                            rules: [{
                                required: true, message: '请上传商品图片',
                            }],
                        })(
                            <Upload {...props}>
                                <Button>
                                    <Icon type="upload" /> upload
                                </Button>
                            </Upload>
                        )}
                    </FormItem>

                    <FormItem
                        label={<span>商品的详细描述</span>}
                    >
                        {getFieldDecorator('goods_desc', {
                            initialValue: data.goods_desc || '',
                            // getValueFromEvent: this.receiveHtml,
                            rules: [{

                            }],
                        })(
                            <LzEditorCom getGoodDesc={this.getGoodDesc}
                                // receiveHtml = {this.receiveHtml}
                                         importContent={this.state.goods_desc}/>
                        )}
                    </FormItem>

                    <Divider style={{ margin: '24px 0' }} />
                    <Form.Item
                        style={{ marginBottom: 8 }}
                        wrapperCol={{
                            xs: { span: 24, offset: 0 },
                            sm: { span: formItemLayout.wrapperCol.span, offset: formItemLayout.labelCol.span },
                        }}
                        label=""
                    >

                        <Button onClick={this.onPrev}>
                            上一步
                        </Button>
                        <Button type="primary" onClick={this.onValidateForm} loading={submitting}  style={{ marginLeft: 8 }}>
                            下一步
                        </Button>
                        <Button type="default" onClick={this.stepSubmit} disabled={isDisplay} style={{marginLeft:'8px'}}>保存</Button>
                    </Form.Item>
                </Form>
            </Card>
        )
    }
}

